//
//  DXNetWorkClient.swift
//  weiBoOfSwift
//
//  Created by simon on 15/12/6.
//  Copyright © 2015年 simon. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
enum requestMethod: String {
  
    case POST = "POST"
    case GET = "GET"
    
}

class DXNetWorkClient: AFHTTPSessionManager {
////    1.单列第一种方法
    static var onceToken:dispatch_once_t = 0
    static var client:DXNetWorkClient?

    static let netWorkClient:DXNetWorkClient = {
        
          dispatch_once(&onceToken, { () -> Void in
            
            client = DXNetWorkClient()
//            client!.responseSerializer.acceptableContentTypes?.insert("text/plain")
            client!.responseSerializer = AFHTTPResponseSerializer()
            
          })
    
    return client!
    }()
//    单例第二种方法
//    static let netWorkClicent:DXNetWorkClient = DXNetWorkClient()
    
   
    // MARK: - 类方法类调用AFN网络请求,对外界的调用接口
    class  func requestNetWork(request:requestMethod,URLStirng:String,parameters: AnyObject?,success:((responser:AnyObject)->())?,failure:(( error:NSError)->())?)->(){
        
    DXNetWorkClient.netWorkClient.requestNetWork(request,URLStirng:URLStirng, parameters: parameters, success: success, failure: failure)
    }
    
    
    
    // MARK: - 对象方法调用AFN网络请求
  private  func requestNetWork(request:requestMethod,URLStirng:String,parameters: AnyObject?,success:((AnyObject)->())?,failure:((NSError)->())?)->(){
//    SVProgressHUD.show()
//    自定义一个闭包和AFN返回来的闭包进行转移,到统一的地方,方便管理,减少代码重复性
    let AFNSuccess = {(dataTask:NSURLSessionDataTask, responder:AnyObject) -> Void in
//        将二进制数据转换为JSON数据
      let json = try! NSJSONSerialization.JSONObjectWithData(responder as! NSData, options:.MutableContainers)

         success!(json)
//         SVProgressHUD.dismiss()
    }

    let AFNFailure = {(dataTask:NSURLSessionDataTask?,error: NSError) -> Void in
        SVProgressHUD.dismiss()
        
        SVProgressHUD.showErrorWithStatus("网络请求失败")
        
          failure!(error)
    }
    
    if request == requestMethod.GET  {
//        调用AFN的网络请求
        GET(URLStirng, parameters: parameters, success: AFNSuccess, failure: AFNFailure)
        
    }else{
        POST(URLStirng, parameters: parameters, success: AFNSuccess, failure: AFNFailure)
    }
}
    class  func requestUploadNetWork(URLStirng:String,parameters: AnyObject?,data:NSData,name:String,fileName:String,success:((AnyObject)->())?,failure:((NSError)->())?)->(){
        
     DXNetWorkClient.netWorkClient.requestUploadNetWork(URLStirng, parameters: parameters, data: data, name: name, fileName: fileName, success: success, failure: failure)
    
    
    
    }
    
//    MARK: - 对象方法调用AFN网络上传数据
   private func requestUploadNetWork(URLStirng:String,parameters: AnyObject?,data:NSData,name:String,fileName:String,success:((AnyObject)->())?,failure:((NSError)->())?)->(){
    
    POST(URLStirng, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
        formData.appendPartWithFileData( data, name: name, fileName: fileName, mimeType: "octet-stream")
        
        }, success: { (_, responder) -> Void in
            success?(responder)
            
        }) { (_, error) -> Void in
            failure?(error)
        }
    }

}

//MARK:发布文字微博
//http://open.weibo.com/wiki/2/statuses/update
//
extension DXNetWorkClient{
    class func statuesUpdata(status:String,sucessClosure:((responser:AnyObject)->())?,failureClosure:((error:NSError)->())?){
     let statuesUpdataUrlString = "https://api.weibo.com/2/statuses/update.json"
    guard let token = DXUserAccountViewModel.shareUserAccount.access_token else{
            logPrint("没有token值")
            return
        }
      let parameters = [
        "access_token":token,
        "status": status
        ]
        self.requestNetWork(.POST, URLStirng: statuesUpdataUrlString, parameters: parameters, success: sucessClosure, failure: failureClosure)
    }
}
//MARK:发布图片微博
//http://open.weibo.com/wiki/2/statuses/upload
//https://upload.api.weibo.com/2/statuses/upload.json
extension DXNetWorkClient{
    
   class func statuesUpload(status:String?,imge:UIImage,sucessClosure:((responser:AnyObject)->())?,failureClosure:((error:NSError)->())?){
    
    let UploadUrlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        guard let token = DXUserAccountViewModel.shareUserAccount.access_token else{
            logPrint("没有token值")
            return
        }
//    判断是文字是否为空
    let statustext:String = status == nil ? "" : status!
 
        let parameters = [
            "access_token":token,
            "status": statustext
        ]
     let data = UIImagePNGRepresentation(imge)!
        
        self.requestUploadNetWork(UploadUrlString, parameters: parameters, data: data, name: "pic", fileName: "ss", success: sucessClosure, failure: failureClosure)

    }
    
}

//MARK:首页请求数据
extension DXNetWorkClient{

    class func loadHomeData(maxid maxid:Int64,sinceid:Int64,sucessClosure:((responser:AnyObject)->())?,failureClosure:((error:NSError)->())?) {
    let homeUrlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
//    let homeUrlString = "http://localhost/Home.json"
    guard let token = DXUserAccountViewModel.shareUserAccount.access_token else{
    logPrint("没有token值")
        
    return
    }
    
    let parameters = [
        "access_token":token,
        "max_id":"\(maxid)",
        "since_id":"\(sinceid)"
    ]
    
        self.requestNetWork(.GET, URLStirng: homeUrlString, parameters: parameters, success: sucessClosure, failure: failureClosure)

  }
}

// MARK:用户登录网络请求
extension DXNetWorkClient{
    // MARK:用户登录网络请求token
    class func loadToken(code code:String,sucessClosure:((responser:AnyObject)->())?,failureClosure:((error:NSError)->())?){
    let tokenAcessUrlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = [
            
            "client_id":KAPPKEY,
            "client_secret":KAPPSECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":KCALLBACKURL
        ]
       self.requestNetWork(.POST, URLStirng: tokenAcessUrlString, parameters: parameters, success: { (responser) -> () in
        sucessClosure!(responser: responser)
        }) { (error) -> () in
        failureClosure!(error:error)
        }
    }
    
    // MARK:用户登录网络请求userInfo
    class func loadUserInfo(account:DXAccountModel,sucessClosure:((responser:AnyObject)->())?,failureClosure:((error:NSError)->())?){
//        http://localhost/userAccount.json
//        let urlString = " http://localhost/userAccount.json"
        let urlString = "https://api.weibo.com/2/users/show.json"
        let userInfoParameters:[String:AnyObject] = [
            "access_token" : account.access_token!,
            "uid" : account.uid
        ]
        self.requestNetWork(.GET, URLStirng: urlString, parameters: userInfoParameters, success: { (responser) -> () in
            
            sucessClosure!(responser: responser)
            
//            let dat = try!NSJSONSerialization.dataWithJSONObject(responser, options:.PrettylogPrinted)
//            dat.writeToFile("/Users/simon/Desktop/userAccount.json", atomically: true)
            
            }) { (error) -> () in
            failureClosure!(error:error)
        }
    }
}
